package middleware

import (
	commonConfig "gin-worked/app/common/config"
	"gin-worked/app/common/model"
	"gin-worked/config"
	"gin-worked/work"
	"github.com/gin-gonic/gin"
)

// CheckLogin 需要登录的验证
func CheckLogin(c *gin.Context) {
	token := c.Request.Header.Get("access-token")

	if token == "" {
		work.ReturnResult(c, 0, "token不存在，请登录", "")
		c.Abort()
		return
	}

	userToken := config.Rdb.Get(config.Rctx, token)

	if userToken.Val() == "" {
		work.ReturnResult(c, 0, "该token不存在", "")
		c.Abort()
		return
	}

	user, userErr := commonConfig.TokenDecrypt(token)

	if userErr != nil {
		work.ReturnResult(c, 0, userErr.Error(), "")
		c.Abort()
		return
	}
	var i = 0

	where := &model.User{
		Id:         user.Id,
		DeleteTime: &i,
	}

	field := []string{"id", "username", "status", "delete_time"}

	info, infoErr := model.GetUserInfo(where, field)

	if infoErr != nil {
		work.ReturnResult(c, 0, infoErr.Error(), "")
		c.Abort()
		return
	}

	if info.Status != 1 {
		work.ReturnResult(c, 0, "该账户已被封,请联系管理员", "")
		c.Abort()
		return
	}
	c.Set("uid", info.Id)
	c.Next() //继续执行后面的业务逻辑

}
